package com.fare.taluo.message;

import java.net.MalformedURLException;
import java.rmi.RemoteException;

import org.apache.log4j.Logger;

import com.fare.taluo.message.exception.MessageException;
import com.huawei.ema.gd.webservice.LoginRequest;
import com.huawei.ema.gd.webservice.LoginResponse;
import com.huawei.ema.gd.webservice.Message;
import com.huawei.ema.gd.webservice.SendMessageRequest;
import com.huawei.ema.gd.webservice.SendMessageResponse;
import com.huawei.ema.gd.webservice.impl.MessageServiceImpl;
import com.huawei.ema.gd.webservice.impl.MessageServiceImplSoapBindingStub;
/**
 * SMS连接，通过hawei的sms.jar的SOAP登陆
 * @author xiangsf 2012-12-10
 *
 */
public class SMSSoapService {

	protected Logger logger = Logger.getLogger(getClass());
	// 登陆成功标识
	private String token = null;
	private java.net.URL url = null;
	private MessageServiceImpl messageService = null;
	private LoginResponse loginResponse = null;
	private boolean hasInit = false;
	private static SMSSoapService _instance = new SMSSoapService();

	private SMSSoapService() {}
	/**
	 * 初始化登陆，成功后，会设置属性token为新值,若为空，则登陆不成功
	 * <p>若hasInit是否初始化为真，则不再进行初始化，但可以修改hasInit值，以便在配置属性发生变化时，重新初始化
	 * @param configuration
	 * @throws MalformedURLException
	 * @throws RemoteException
	 */
	public SMSSoapService init(SMSMessageProperties configuration) throws MalformedURLException, RemoteException {
		if(!hasInit){
			url = new java.net.URL(configuration.getSmsServer());
			messageService = new MessageServiceImplSoapBindingStub(url, null);
			loginResponse = messageService.login(new LoginRequest(configuration
					.getSmsPwd(), configuration.getSmsUser()));

			if (loginResponse.getResult() == 0) {
				token = loginResponse.getToken();
			}
			hasInit = true;
		}
		return _instance;
	}

	public boolean isHasInit() {
		return hasInit;
	}

	public void setHasInit(boolean hasInit) {
		this.hasInit = hasInit;
	}

	public String getToken() {
		return token;
	}

	public static SMSSoapService getInstance() {
		if (_instance == null) {
			_instance = new SMSSoapService();
		}
		return _instance;
	}
	/**
	 * 发送短信
	 * @param message
	 * @throws RemoteException
	 * @throws MessageException
	 */
	public void send(Message message) throws RemoteException, MessageException {
		SendMessageRequest sendRequest = new SendMessageRequest(
				new Message[] { message }, token);
		SendMessageResponse sendResponse = messageService
				.sendMessage(sendRequest);

		if (sendResponse.getResult() != 0) {
			logger.error(String.format("发送短信给[%s]失败!", message.getAccount()));
			throw new MessageException(sendResponse.getErrorDescription());
		}
	}
}
